package com.sghd.candy.module.element.manager;

import com.sghd.common.ramcache.IEntity;
import com.sghd.common.ramcache.PerPersist;
import com.sghd.common.ramcache.anno.Cached;
import com.sghd.common.ramcache.anno.CachedSizes;
import com.sghd.common.ramcache.anno.Persister;
import com.sghd.common.ramcache.anno.Persisters;
import com.sghd.common.ramcache.enhance.Enhance;
import com.sghd.common.utils.json.JsonUtils;
import com.sghd.pojo.fight.game.ChessType;

import javax.persistence.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Allen
 * @date 2018/12/13
 */
@Entity
@Table(catalog = "bsdld")
@Cached(size = CachedSizes.DEFAULT, persister = @Persister(Persisters.PRE_10_MINUTE))
public class PlayerElement implements IEntity<Long>, PerPersist {
    /**玩家Id*/
    @Id
    private Long playerId;

    /**玩家五行等级*/
    @Transient
    private Map<ChessType, Integer> elements;
    @Lob
    private String elementsJson;

    /**五行通用点数*/
    private Integer dianShu;

    public Long getPlayerId() {
        return playerId;
    }

    void setPlayerId(Long playerId) {
        this.playerId = playerId;
    }

    public Map<ChessType, Integer> getElements() {
        if (this.elements == null) {
            this.elements = new HashMap<>();
        }

        return new HashMap<>(this.elements);
    }

    void setElements(Map<ChessType, Integer> elements) {
        this.elements = elements;
    }

    public String getElementsJson() {
        return elementsJson;
    }

    void setElementsJson(String elementsJson) {
        this.elementsJson = elementsJson;
    }

    public Integer getDianShu() {
        return dianShu;
    }

    public void setDianShu(Integer dianShu) {
        this.dianShu = dianShu;
    }

    static PlayerElement valueOf(long playerId) {
        PlayerElement playerElement = new PlayerElement();
        playerElement.playerId = playerId;
        playerElement.setElements(new HashMap<>(5));
        playerElement.elements.put(ChessType.CT_BLUE, 0);
        playerElement.elements.put(ChessType.CT_GREEN, 0);
        playerElement.elements.put(ChessType.CT_PURPLE, 0);
        playerElement.elements.put(ChessType.CT_RED, 0);
        playerElement.elements.put(ChessType.CT_YELLOW, 0);
        playerElement.setDianShu(0);
        return playerElement;
    }

    @Enhance
    void change(int changeNum) {
        setDianShu(getDianShu() + changeNum);
    }

    @Enhance
    void upgrade(ChessType chessType) {
        //TODO 五行升级
        this.elements.put(chessType, this.elements.get(chessType) + 1);
    }


    @Override
    public Long getId() {
        return this.playerId;
    }

    @Override
    public void afterLoad() {
        elements = JsonUtils.string2Map(elementsJson, ChessType.class, Integer.class);
    }

    @Override
    public void beforePersist() {
        elementsJson = JsonUtils.object2String(elements);
    }
}
